<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-tabs">
        <span :class="{active: mode==='login'}" @click="mode='login'">密码登录</span>
        <span :class="{active: mode==='sms-login'}" @click="mode='sms-login'">验证码登录</span>
        <span :class="{active: mode==='register'}" @click="mode='register'">注册</span>
      </div>
      
      <!-- 密码登录表单 -->
      <form v-if="mode==='login'" @submit.prevent="handlePasswordLogin">
        <div class="form-group">
          <input v-model="passwordForm.username" type="text" placeholder="用户名" required />
        </div>
        <div class="form-group">
          <input v-model="passwordForm.password" type="password" placeholder="密码" required />
        </div>
        <button class="submit-btn" type="submit">登录</button>
      </form>

      <!-- 验证码登录表单 -->
      <form v-if="mode==='sms-login'" @submit.prevent="handleSmsLogin">
        <div class="form-group">
          <input v-model="smsForm.phone" type="text" placeholder="手机号" required />
        </div>
        <div class="form-group captcha-group">
          <input v-model="smsForm.imageCode" type="text" placeholder="图片验证码" required maxlength="4" />
          <div class="captcha-image" @click="refreshCaptcha">
            <img v-if="captchaImage" :src="captchaImage" alt="验证码" />
            <div v-else class="captcha-loading">加载中...</div>
          </div>
        </div>
        <div class="form-group sms-code-group">
          <input v-model="smsForm.code" type="text" placeholder="短信验证码" required maxlength="6" />
          <button 
            type="button" 
            class="send-code-btn" 
            @click="sendSmsCode"
            :disabled="smsForm.countdown > 0"
          >
            {{ smsForm.countdown > 0 ? `${smsForm.countdown}s` : '获取验证码' }}
          </button>
        </div>
        <button class="submit-btn" type="submit">登录</button>
      </form>

      <!-- 注册表单 -->
      <form v-if="mode==='register'" @submit.prevent="handleRegister">
        <div class="form-group">
          <input v-model="registerForm.username" type="text" placeholder="用户名" required />
        </div>
        <div class="form-group">
          <input v-model="registerForm.password" type="password" placeholder="密码" required />
        </div>
        <div class="form-group">
          <input v-model="registerForm.phone" type="text" placeholder="手机号（可选）" />
        </div>
        <div class="form-group">
          <input v-model="registerForm.email" type="email" placeholder="邮箱（可选）" />
        </div>
        <div class="form-group avatar-upload">
          <label class="avatar-label">
            <input type="file" @change="onAvatarChange" accept="image/*" hidden />
            <div class="avatar-preview" v-if="avatarUrl">
              <img :src="avatarUrl" alt="头像预览" />
              <span class="remove-avatar" @click.stop="removeAvatar">×</span>
            </div>
            <div v-else class="upload-btn">
              <span>上传头像</span>
            </div>
          </label>
        </div>
        <button class="submit-btn" type="submit">注册</button>
      </form>

      <div class="switch-tip">
        <span v-if="mode==='login'">
          没有账号？<span @click="mode='register'">去注册</span>
        </span>
        <span v-if="mode==='login'">
          或 <span @click="mode='sms-login'">验证码登录</span>
        </span>
        <span v-if="mode==='sms-login'">
          没有账号？<span @click="mode='register'">去注册</span>
        </span>
        <span v-if="mode==='sms-login'">
          或 <span @click="mode='login'">密码登录</span>
        </span>
        <span v-if="mode==='register'">
          已有账号？<span @click="mode='login'">去登录</span>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Auth',
  data() {
    return {
      mode: 'login',
      // 密码登录表单
      passwordForm: {
        username: '',
        password: ''
      },
      // 验证码登录表单
      smsForm: {
        phone: '',
        imageCode: '',
        code: '',
        countdown: 0
      },
      // 注册表单
      registerForm: {
        username: '',
        password: '',
        phone: '',
        email: '',
        avatar: null
      },
      avatarUrl: '',
      // 图片验证码相关
      captchaImage: '',
      captchaUuid: ''
    }
  },
  mounted() {
    // 页面加载时生成UUID
    this.generateUuid()
  },
  watch: {
    mode(newMode) {
      if (newMode === 'sms-login') {
        this.generateUuid()
      }
    }
  },
  methods: {
    // 生成UUID
    generateUuid() {
      this.captchaUuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c == 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
      this.loadCaptcha()
    },

    // 加载图片验证码
    async loadCaptcha() {
      try {
        const response = await this.$axios.get(`http://localhost:8000/accounts/getimagecode/?uuid=${this.captchaUuid}`, {
          responseType: 'blob'
        })
        this.captchaImage = URL.createObjectURL(response.data)
      } catch (error) {
        console.error('加载验证码失败:', error)
        alert('验证码加载失败，请刷新页面重试')
      }
    },

    // 刷新验证码
    refreshCaptcha() {
      this.generateUuid()
      // 不清空输入框，让用户自己决定是否清空
    },

    // 密码登录
    async handlePasswordLogin() {
      try {
        const res = await this.$api.post('/accounts/login/', {
          username: this.passwordForm.username,
          password: this.passwordForm.password
        });
        if (res.data.token) {
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('retoken', res.data.retoken || '');
          localStorage.setItem('user', JSON.stringify(res.data.user));
          alert('登录成功！');
          // 登录成功后跳转
          this.$router.push('/dashboard');
        } else {
          alert(res.data.msg || '登录失败');
        }
      } catch (err) {
        alert(err.response?.data?.msg || '登录失败');
      }
    },

    // 发送验证码
    async sendSmsCode() {
      if (!this.smsForm.phone) {
        alert('请输入手机号');
        return;
      }
      
      if (!this.smsForm.imageCode) {
        alert('请输入图片验证码');
        return;
      }
      
      // 验证手机号格式
      const phonePattern = /^1[3-9]\d{9}$/;
      if (!phonePattern.test(this.smsForm.phone)) {
        alert('请输入正确的手机号');
        return;
      }

      try {
        const formData = new FormData();
        formData.append('phone', this.smsForm.phone);
        formData.append('image_code', this.smsForm.imageCode);
        formData.append('uuid', this.captchaUuid);

        const res = await this.$api.post('/accounts/send-sms/', formData);
        
        if (res.data.msg.includes('成功')) {
          alert('验证码发送成功！');
          this.startCountdown();
          // 发送成功时不刷新图片验证码，保持用户输入
        } else {
          alert(res.data.msg || '验证码发送失败');
          // 发送失败时刷新图片验证码
          this.refreshCaptcha();
        }
      } catch (err) {
        alert(err.response?.data?.msg || '验证码发送失败');
        // 发送失败时刷新图片验证码
        this.refreshCaptcha();
      }
    },

    // 验证码登录
    async handleSmsLogin() {
      if (!this.smsForm.phone || !this.smsForm.code) {
        alert('请输入手机号和验证码');
        return;
      }

      try {
        const res = await this.$api.post('/accounts/sms-login/', {
          phone: this.smsForm.phone,
          code: this.smsForm.code
        });
        
        if (res.data.token) {
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('retoken', res.data.retoken || '');
          localStorage.setItem('user', JSON.stringify(res.data.user));
          alert('登录成功！');
          // 登录成功后跳转
          this.$router.push('/dashboard');
        } else {
          alert(res.data.msg || '登录失败');
        }
      } catch (err) {
        if (err.response?.data?.code === 'USER_NOT_EXISTS') {
          // 用户不存在，提示去注册
          if (confirm('该手机号未注册，是否跳转到注册页面？')) {
            this.mode = 'register';
            // 自动填充手机号
            this.registerForm.phone = this.smsForm.phone;
          }
        } else {
          alert(err.response?.data?.msg || '登录失败');
        }
      }
    },

    // 注册
    async handleRegister() {
      const formData = new FormData();
      formData.append('username', this.registerForm.username);
      formData.append('password', this.registerForm.password);
      if (this.registerForm.phone) formData.append('phone', this.registerForm.phone);
      if (this.registerForm.email) formData.append('email', this.registerForm.email);
      if (this.registerForm.avatar) formData.append('avatar', this.registerForm.avatar);
      
      try {
        const res = await this.$api.post('/accounts/register/', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.data.token) {
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('retoken', res.data.retoken || '');
          localStorage.setItem('user', JSON.stringify(res.data.user));
          alert('注册成功！');
          // 注册成功后跳转
          this.$router.push('/dashboard');
        } else {
          alert(res.data.msg || '注册失败');
        }
      } catch (err) {
        alert(err.response?.data?.msg || '注册失败');
      }
    },

    // 开始倒计时
    startCountdown() {
      this.smsForm.countdown = 60;
      const timer = setInterval(() => {
        this.smsForm.countdown--;
        if (this.smsForm.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },

    // 头像相关方法
    onAvatarChange(e) {
      const file = e.target.files[0];
      this.registerForm.avatar = file;
      if (file) {
        const reader = new FileReader();
        reader.onload = e2 => {
          this.avatarUrl = e2.target.result;
        };
        reader.readAsDataURL(file);
      } else {
        this.avatarUrl = '';
      }
    },
    removeAvatar() {
      this.registerForm.avatar = null;
      this.avatarUrl = '';
    }
  }
}
</script>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f7f4f1 0%, #e9e3db 100%);
}
.auth-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(140, 90, 50, 0.08);
  padding: 40px 32px 24px 32px;
  min-width: 340px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.auth-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
}
.auth-tabs span {
  font-size: 1rem;
  color: #a88b6a;
  margin: 0 12px;
  cursor: pointer;
  padding-bottom: 4px;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
  white-space: nowrap;
}
.auth-tabs .active {
  color: #7a5232;
  border-bottom: 2px solid #7a5232;
}
.form-group {
  margin-bottom: 18px;
  width: 240px;
}
.captcha-group {
  display: flex;
  gap: 8px;
}
.captcha-group input {
  flex: 1;
}
.captcha-image {
  width: 120px;
  height: 45px;
  border: 1px solid #e0d6c8;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #faf7f3;
  overflow: hidden;
}
.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.captcha-loading {
  color: #a88b6a;
  font-size: 0.8rem;
}
.sms-code-group {
  display: flex;
  gap: 8px;
}
.sms-code-group input {
  flex: 1;
}
.send-code-btn {
  padding: 10px 12px;
  background: #8b5c37;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 0.9rem;
  cursor: pointer;
  white-space: nowrap;
  transition: background 0.2s;
}
.send-code-btn:hover:not(:disabled) {
  background: #7a5232;
}
.send-code-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
input[type="text"], input[type="password"], input[type="email"] {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #e0d6c8;
  border-radius: 6px;
  font-size: 1rem;
  outline: none;
  background: #faf7f3;
  color: #7a5232;
}
.avatar-upload {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.avatar-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.avatar-preview {
  position: relative;
  width: 48px;
  height: 48px;
  margin-right: 12px;
}
.avatar-preview img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e0d6c8;
}
.remove-avatar {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #fff;
  color: #a88b6a;
  border: 1px solid #e0d6c8;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.1rem;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(140, 90, 50, 0.08);
}
.upload-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background: #faf7f3;
  border: 2px dashed #e0d6c8;
  border-radius: 50%;
  color: #a88b6a;
  font-size: 0.95rem;
  cursor: pointer;
  transition: border 0.2s;
}
.upload-btn:hover {
  border: 2px solid #a88b6a;
}
.submit-btn {
  width: 100%;
  padding: 10px 0;
  background: #8b5c37;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 1.1rem;
  cursor: pointer;
  margin-top: 8px;
  transition: background 0.2s;
}
.submit-btn:hover {
  background: #7a5232;
}
.switch-tip {
  margin-top: 18px;
  color: #a88b6a;
  font-size: 0.9rem;
  text-align: center;
  line-height: 1.5;
}
.switch-tip span {
  color: #7a5232;
  cursor: pointer;
  margin-left: 4px;
  text-decoration: underline;
}
</style> 